package com.atguigu.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.AdminRoleDao;
import com.atguigu.dao.RoleDao;
import com.atguigu.entity.AdminRole;
import com.atguigu.entity.Role;
import com.atguigu.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Transactional
@Service(interfaceClass = RoleService.class)
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private AdminRoleDao adminRoleDao;
    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public Map<String, Object> findRoleByAdminId(Long adminId) {
          //获取所有的角色
        List<Role> roleList = this.roleDao.findAll();
        //获取当前用户角色id列表
      List<Long> roleIdList  =adminRoleDao.findRoleIdsByAdminId(adminId);
       //  根据当前用户角色的id  将所有角色分成两部分  已分配和未分配
        List<Role> noAssignRoleList = new ArrayList<>();
        List<Role> assignRoleList =new ArrayList<>();

        for (Role role :roleList){
            //已分配
            if(roleIdList.contains(role.getId())){
                assignRoleList.add(role);
            }else{
                noAssignRoleList.add(role);
            }
        }
         Map<String,Object> roleMap =new HashMap<>();
        roleMap.put("noAssignRoleList",noAssignRoleList);
        roleMap.put("assignRoleList",assignRoleList);
        return  roleMap;
    }



//    功能是分配角色
    @Override
    public void saveUserRoleRealtionship(Long adminId,  Long[] roleIds) {

          //删除之前的角色列表
        adminRoleDao.deleteByAdminId(adminId);
        if(roleIds!=null){
            for (Long roleId :roleIds) {
                if(!StringUtils.isEmpty(roleId)) {
                    AdminRole userRole = new AdminRole();
                    userRole.setAdminId(adminId);
                    userRole.setRoleId(roleId);
                    adminRoleDao.insert(userRole);
                }
            }

        }


    }


    @Override
    protected BaseDao<Role> getEntityDao() {

        return roleDao;
    }
}
